package com.migu.contacts.main;

import static com.migu.contacts.net.Service.API;

import android.content.Intent;
import android.util.Log;
import android.view.View;

import androidx.annotation.NonNull;
import androidx.appcompat.widget.SearchView;
import androidx.recyclerview.widget.LinearLayoutManager;
import androidx.recyclerview.widget.RecyclerView;

import com.frank.libandroid.BaseActivity;
import com.frank.libandroid.BaseAdapter;
import com.frank.libandroid.BottomPopup;
import com.frank.libandroid.DataStore;
import com.frank.libandroid.GsonUtil;
import com.frank.libandroid.HttpCallback;
import com.frank.libandroid.Key;
import com.frank.libandroid.butterknife.BindAdapter;
import com.frank.libandroid.butterknife.OnClick;
import com.frank.libandroid.util.ImageUtil;
import com.google.android.flexbox.FlexDirection;
import com.google.android.flexbox.FlexboxLayoutManager;
import com.lxj.xpopup.XPopup;
import com.migu.contacts.R;
import com.migu.contacts.bean.ContactBean;
import com.migu.contacts.bean.GroupBean;
import com.migu.contacts.bean.LetterBean;
import com.migu.contacts.databinding.ActivityContactSelectBinding;
import com.migu.contacts.databinding.ContactSelectPopAddBinding;
import com.migu.contacts.databinding.ContactSelectPopBinding;
import com.migu.contacts.databinding.ItemSelectContactBinding;
import com.migu.contacts.databinding.ItemSelectContactCheckedBinding;
import com.migu.contacts.databinding.ItemSelectContactConfirmBinding;
import com.migu.contacts.databinding.ItemSelectContactLetterBinding;
import com.migu.contacts.databinding.ItemSelectGroupBinding;
import com.migu.contacts.databinding.ItemSelectGroupDetailBinding;
import com.migu.contacts.util.AvatarUtil;
import com.migu.contacts.util.GroupUtil;

import java.util.ArrayList;
import java.util.Comparator;
import java.util.HashSet;
import java.util.List;
import java.util.Set;
import java.util.TreeSet;
import java.util.function.Predicate;

public class ContactSelectActivity extends BaseActivity<ActivityContactSelectBinding> {
    ContactBean contactBean = DataStore.remove(this.getClass().getName());

    @Override
    protected void initView() {
        super.initView();
        mBinding.searchView.setOnQueryTextListener(new SearchView.OnQueryTextListener() {
            @Override
            public boolean onQueryTextSubmit(String query) {
                return false;
            }

            @Override
            public boolean onQueryTextChange(String newText) {
                return false;
            }
        });
        LinearLayoutManager layoutManager = (LinearLayoutManager) mBinding.selectedRecyclerView.getLayoutManager();
        layoutManager.setOrientation(LinearLayoutManager.HORIZONTAL);
        mBinding.recyclerView.addOnScrollListener(new RecyclerView.OnScrollListener() {
            @Override
            public void onScrolled(@NonNull RecyclerView recyclerView, int dx, int dy) {
                super.onScrolled(recyclerView, dx, dy);
                RecyclerView.LayoutManager layoutManager1 = recyclerView.getLayoutManager();
                int firstVisibleItemPosition = layoutManager1.getPosition(recyclerView.getChildAt(0));
                String firstLetter = adapter.getData().get(firstVisibleItemPosition).firstLetter;
                List<LetterBean> data = letterAdapter.getData();
                for (LetterBean datum : data) {
                    if (datum.letter.equals(firstLetter)) {
                        datum.checked = true;
                    } else {
                        datum.checked = false;
                    }
                }
                letterAdapter.notifyDataSetChanged();
            }
        });
    }

    @Override
    protected void initData() {
        super.initData();
        API.queryGroup().watch(this, new HttpCallback<List<GroupBean>>() {
            @Override
            protected void onSuccess(List<GroupBean> groupBeans) {
                GroupUtil.setGroups(groupBeans);

            }
        });
        API.contactsAll().watch(this, new HttpCallback<List<ContactBean>>() {
            @Override
            protected void onSuccess(List<ContactBean> contactBeans) {
                Log.d(TAG, "onSuccess() called with: contactBeans = [" + contactBeans + "]");
                contactBeans.removeIf(new Predicate<ContactBean>() {
                    @Override
                    public boolean test(ContactBean bean) {
                        return contactBean.id == bean.id;
                    }
                });
                for (ContactBean contactBean : contactBeans) {
                    contactBean.firstLetter = contactBean.namePinyin.substring(0, 1).toUpperCase();
                }
                contactBeans.sort(new Comparator<ContactBean>() {
                    @Override
                    public int compare(ContactBean o1, ContactBean o2) {
                        return o1.namePinyin.compareTo(o2.namePinyin);
                    }
                });
                adapter.setData(contactBeans);
                TreeSet<String> letters = new TreeSet<>();
                for (ContactBean contactBean : contactBeans) {
                    letters.add(contactBean.firstLetter);
                }
                List<LetterBean> letterBeanList = new ArrayList<>();
                for (String letter : letters) {
                    LetterBean e = new LetterBean();
                    e.letter = letter;
                    letterBeanList.add(e);
                }
                letterAdapter.setData(letterBeanList);
            }
        });
    }

    @BindAdapter(R.id.recyclerView)
    BaseAdapter<ItemSelectContactBinding, ContactBean> adapter = new BaseAdapter<ItemSelectContactBinding, ContactBean>() {

        @Override
        protected void onBindData(ItemSelectContactBinding binding, ContactBean bean, int position) {
            super.onBindData(binding, bean, position);
            int avatar = AvatarUtil.getAvatar(bean.gender);
            binding.avatar.setImageResource(avatar);
            if (position > 0 && mList.get(position - 1).firstLetter.equals(bean.firstLetter)) {
                binding.firstLetter.setVisibility(View.GONE);
            } else {
                binding.firstLetter.setVisibility(View.VISIBLE);
            }
            LinearLayoutManager layoutManager = (LinearLayoutManager) binding.groupRecyclerView.getLayoutManager();
            layoutManager.setOrientation(LinearLayoutManager.HORIZONTAL);
            BaseAdapter<ItemSelectGroupDetailBinding, GroupBean> groupBeanBaseAdapter = new BaseAdapter<ItemSelectGroupDetailBinding, GroupBean>() {
            };
            binding.groupRecyclerView.setAdapter(groupBeanBaseAdapter);
            groupBeanBaseAdapter.setData(bean.relationGroupList);
            binding.check.setOnClickListener(new View.OnClickListener() {
                @Override
                public void onClick(View v) {
                    bean.checked = binding.check.isChecked();
                    if (bean.checked) {
                        API.queryGroup().watch(mActivity, new HttpCallback<List<GroupBean>>() {
                            @Override
                            protected void onSuccess(List<GroupBean> groupBeans) {
                                add(bean, groupBeans);
                            }
                        });
                    } else {
                        selectedList.remove(bean);
                        selectedAdapter.setData(selectedList);
                        ContactSelectActivity.this.mBinding.text.setText("已选择(" + selectedList.size() + ")");
                    }
                }
            });
            binding.check.setChecked(bean.checked);
        }
    };

    private void add(ContactBean bean, List<GroupBean> groupBeans) {
        BottomPopup bottomPopup = new BottomPopup<ContactSelectPopAddBinding>(mActivity) {
            @OnClick(R.id.close)
            public void quit() {
                dismiss();
            }

            @OnClick(R.id.confirm)
            public void confirm() {
                if (bean.relationGroupList == null) {
                    bean.relationGroupList = new ArrayList<>();
                }
                bean.relationGroupList.clear();
                for (GroupBean datum : myAdapter.getData()) {
                    if (datum.isChecked) {
                        bean.relationGroupList.add(datum);
                    }
                }
                selectedList.add(bean);
                selectedAdapter.setData(selectedList);
                adapter.notifyDataSetChanged();
                ContactSelectActivity.this.mBinding.text.setText("已选择(" + selectedList.size() + ")");
                dismiss();
            }

            @Override
            protected void initData() {
                super.initData();
            }

            @Override
            protected void initView() {
                super.initView();
                FlexboxLayoutManager layoutManager = (FlexboxLayoutManager) mBinding.recyclerView.getLayoutManager();
                layoutManager.setFlexDirection(FlexDirection.ROW);
                mBinding.recyclerView.setAdapter(myAdapter);
                myAdapter.setData(groupBeans);
            }

            BaseAdapter<ItemSelectGroupBinding, GroupBean> myAdapter = new BaseAdapter<ItemSelectGroupBinding, GroupBean>() {
                @OnClick(R.id.text)
                public void text(GroupBean bean, ItemSelectGroupBinding binding) {
                    binding.text.setSelected(!binding.text.isSelected());
                    bean.isChecked = binding.text.isSelected();
                }

                @Override
                protected void onBindData(ItemSelectGroupBinding binding, GroupBean bean, int position) {
                    super.onBindData(binding, bean, position);
                }
            };

        };
        new XPopup.Builder(mActivity).asCustom(bottomPopup).show();
    }

    Set<ContactBean> selectedList = new HashSet<>();
    @BindAdapter(R.id.letters)
    BaseAdapter<ItemSelectContactLetterBinding, LetterBean> letterAdapter = new BaseAdapter<ItemSelectContactLetterBinding, LetterBean>() {
    };
    @BindAdapter(R.id.selectedRecyclerView)
    BaseAdapter<ItemSelectContactCheckedBinding, ContactBean> selectedAdapter = new BaseAdapter<ItemSelectContactCheckedBinding, ContactBean>() {
        @Override
        protected void onBindData(ItemSelectContactCheckedBinding binding, ContactBean bean, int position) {
            super.onBindData(binding, bean, position);
            ImageUtil.loadImage(binding.avatar, AvatarUtil.getAvatar(bean.gender));
            binding.getRoot().setOnClickListener(new View.OnClickListener() {
                @Override
                public void onClick(View v) {
                    remove(v);
                }
            });
        }
    };

    public void remove(View view) {
        BottomPopup bottomPopup = new BottomPopup<ContactSelectPopBinding>(mActivity) {
            @OnClick(R.id.close)
            public void quit() {
                dismiss();
                selectedAdapter.setData(selectedList);
                adapter.notifyDataSetChanged();
            }

            @Override
            protected void initData() {
                super.initData();
            }

            @Override
            protected void initView() {
                super.initView();
                mBinding.header.setText("已选择(" + selectedList.size() + ")");
                mBinding.recyclerView.setAdapter(myAdapter);
                myAdapter.setData(selectedList);
            }

            BaseAdapter<ItemSelectContactConfirmBinding, ContactBean> myAdapter = new BaseAdapter<ItemSelectContactConfirmBinding, ContactBean>() {
                @OnClick(R.id.remove)
                public void remove(ContactBean bean) {
                    selectedList.remove(bean);
                    bean.checked = false;
                    myAdapter.setData(selectedList);
                    ContactSelectActivity.this.mBinding.text.setText("已选择(" + selectedList.size() + ")");
                    mBinding.header.setText("已选择(" + selectedList.size() + ")");
                }

                @Override
                protected void onBindData(ItemSelectContactConfirmBinding binding, ContactBean bean, int position) {
                    super.onBindData(binding, bean, position);
                    int avatar = AvatarUtil.getAvatar(bean.gender);
                    binding.avatar.setImageResource(avatar);
                    LinearLayoutManager layoutManager = (LinearLayoutManager) binding.groupRecyclerView.getLayoutManager();
                    layoutManager.setOrientation(LinearLayoutManager.HORIZONTAL);
                    BaseAdapter<ItemSelectGroupDetailBinding, GroupBean> groupBeanBaseAdapter = new BaseAdapter<ItemSelectGroupDetailBinding, GroupBean>() {
                    };
                    binding.groupRecyclerView.setAdapter(groupBeanBaseAdapter);
                    groupBeanBaseAdapter.setData(bean.relationGroupList);
                }
            };

        };
        new XPopup.Builder(mActivity).asCustom(bottomPopup).show();
    }

    public static final Key<Set<ContactBean>> KEY_CONTACTS = new Key<Set<ContactBean>>();

    public void save(View view) {
        Intent intent = new Intent();
        intent.putExtra("group", GsonUtil.toJson(selectedList));
        setResult(RESULT_OK, intent);
        DataStore.put(KEY_CONTACTS, selectedList);
        finish();
    }
}